package com.doge.calcalbum.business.note

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import com.doge.calcalbum.R
import com.doge.calcalbum.analysis.analysisEvent
import com.doge.calcalbum.analysis.insert_note
import com.doge.calcalbum.analysis.page_note
import com.doge.calcalbum.api.observeOnMain
import com.doge.calcalbum.api.subscribeOnIO
import com.doge.calcalbum.core.BaseActivity
import com.doge.calcalbum.core.base.LoadStatus
import com.doge.calcalbum.core.base.isRefreshing
import com.doge.calcalbum.databinding.ActivityNoteEditBinding
import com.doge.calcalbum.utils.appContext
import com.doge.calcalbum.utils.setOnClickCallback
import com.doge.calcalbum.utils.systemWindowInsetsTop
import com.doge.calcalbum.utils.toast
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit
import kotlin.math.min

class NoteEditActivity : BaseActivity() {
    private val binding by lazy { ActivityNoteEditBinding.inflate(layoutInflater) }
    private val noteId: Int? by lazy {
        intent.getIntExtra(EXTRA_NOTE_ID, -1).let { if (it == -1) null else it }
    }
    private val viewModel by viewModels<NoteViewModel> { NoteViewModelFactory() }
    private var autoTask: Disposable? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        analysisEvent(page_note)
        systemWindowInsetsTop.observe(this) {
            binding.fitsSys.setPadding(it / 2)
        }
        binding.pageBack.setOnClickCallback { finish() }
        binding.upload.setOnClickCallback { update() }
        viewModel.loading.observe(this) {
            if (it.isRefreshing()) {
                binding.loadingUpload.isVisible = true
                binding.upload.alpha = 0.5f
            } else if (it == LoadStatus.SUCCESS) {
                toast(R.string.save_completed)
                finish()
            }
        }
        viewModel.noteContent.observe(this) {
            binding.content.setText(it)
            binding.content.setSelection(it.length)
        }
        noteId?.let { viewModel.query(it) }

        autoTask = Observable.timer(100, TimeUnit.MILLISECONDS)
            .subscribeOnIO()
            .observeOnMain()
            .doOnNext {
                binding.content.requestFocus()
                ContextCompat.getSystemService(appContext, InputMethodManager::class.java)
                    ?.showSoftInput(binding.content, 0)
            }
            .subscribe()
    }

    private fun update() {
        val content = binding.content.text.trim().toString()
        val maxLength = min(24, content.length)
        val idx = content.indexOf("\n").let { if (it == -1) maxLength else it }
        val title = content.substring(0, idx)
        viewModel.edit(noteId, title, content)
        analysisEvent(insert_note)
    }

    override fun finish() {
        super.finish()
        autoTask?.dispose()
    }

    companion object {
        private const val EXTRA_NOTE_ID = "noteId"
        fun start(context: Context?, noteId: Int? = null) {
            if (context == null) return
            context.startActivity(Intent(context, NoteEditActivity::class.java).apply {
                noteId?.let { putExtra(EXTRA_NOTE_ID, noteId) }
            })
        }
    }
}